package com.luoqy.speedy.util.aop.log;

import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.luoqy.speedy.core.cache.CacheServiceImpl;
import com.luoqy.speedy.data.DataBase;
import com.luoqy.speedy.data.MySql;
import com.luoqy.speedy.util.IpAddressUtils;
import com.luoqy.speedy.util.ReqParams;
import com.luoqy.speedy.util.Result;

/**
 *  切面处理方法
 *      日志操控记录
 * */
@Aspect
@Component
public class LogAspect {
	long time=0L;
    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("execution(* *(..)) && @annotation(com.luoqy.speedy.util.aop.log.Log)")
    public void logPoinCut() {
    	System.err.println("logPoinCut");
    }
    @Around("logPoinCut()")
    public Object handlingTimeAround(ProceedingJoinPoint joinPoint) throws Throwable{
    	long startTime = System.currentTimeMillis();
        try {
            Object result = joinPoint.proceed();
			time=(System.currentTimeMillis() - startTime);
			return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw throwable;
        }
    }
    //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) throws Throwable {
    	long startTime = System.currentTimeMillis();
    	StringBuffer set=new StringBuffer(" insert into speedy_handlelog set ");
    	//保存日志
        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        //获取操作
        Log myLog = method.getAnnotation(Log.class);
        if (myLog != null) {
            //注册值
            String[] values = myLog.value();//保存获取的操作
            for (int i = 0; i < values.length; i++) {
				if(i==0){
					 //操作描述
		            String handleDesc=values[0];
		            set.append("handledesc=\"");
		            set.append(handleDesc);
		            set.append("\",");
				}
				if(i==1){
					 //其他描述
		            String handleOther=values[1];
		            set.append("handleother=\"");
		            set.append(handleOther);
		            set.append("\",");
				}
			}
           
           
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        
        //获取请求的类名
        Enumeration<String> json=request.getParameterNames();
        Map<String,String> params=new HashMap<String,String>();
        while(json.hasMoreElements()){
        	String name=json.nextElement();
        	String value=request.getParameter(name);
        	if("content".equals(name)){
        		params.put(name, URLEncoder.encode(value,"UTF-8"));
        	}else{
        		params.put(name, value);
        	}
        	
        	
        }
        set.append("params=\"");
        set.append(params);
        set.append("\",");
        //请求URL地址
        set.append("url=\"");
        set.append(request.getRequestURL().toString());
        set.append("\",");
        //返回的参数
        
        HttpServletResponse response= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
         ProceedingJoinPoint  s=(ProceedingJoinPoint) joinPoint;
         //这里再次执行了方法
        //请求类名
          String className = joinPoint.getTarget().getClass().getName();
        set.append("classname=\"");
        set.append(className);
        set.append("\",");
        //获取请求的方法名
        String methodName = method.getName();
        set.append("method=\"");
        set.append(methodName);
        set.append("\",");
        //获取用户名
        HttpSession session=request.getSession(true);
        Object user=session.getAttribute("user");
        set.append("user=\"");
        set.append(user);
        set.append("\",");
        //获取用户ip地址
        String ip=IpAddressUtils.INTERNET_IP;
        set.append("ip=\"");
        set.append(ip);
        set.append("\",");
       
        CacheServiceImpl resultCache=new CacheServiceImpl();
        Result result=(Result)resultCache.getCacheDataByKey("result");
//         Result result=(Result) s.proceed();
       Map<String, Object> resultMap=ReqParams.beanToMap(result);
       if(null!=resultMap.get("data")){
    	  String data=""+resultMap.get("data");
    	  if(data.contains("content")&&data.contains("style")){
    		  resultMap.put("data","因是字符编码所以取消显示");
    	  }
       	
       }
      
       set.append("result=\"");
       set.append(resultMap);
       set.append("\",");
       //执行时间
       set.append("time=");
       set.append(time);
        //调用service保存SysLog实体类到数据库
        MySql.EXECUTE(set.toString(),new DataBase());
    }
}
